import { useEffect, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import axios from 'axios'; // Add axios import
import { wxAuthConfig } from '../config'; // Update config import path
import PropTypes from 'prop-types';

export default function WechatLogin({ onLoginSuccess }) {
  const [qrcodeUrl, setQrcodeUrl] = useState('');
  const [scanStatus, setScanStatus] = useState('waiting');
  const [state, setState] = useState(''); // Add state variable

  // 生成微信登录二维码
  useEffect(() => {
    const generateQRCode = async () => {
      const state = Math.random().toString(36).substr(2);
      setState(state); // Update state variable
      const url = `https://open.weixin.qq.com/connect/qrconnect?appid=${wxAuthConfig.appId}&redirect_uri=${encodeURIComponent(wxAuthConfig.redirectUri)}&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect`;
      setQrcodeUrl(url);
    };
    generateQRCode();
  }, []);

  // useEffect(() => {
  //   const pollStatus = setInterval(async () => {
  //     try {
  //       const res = await axios.get('/api/auth/wechat/status', {
  //         params: { state }
  //       });
  //       if (res.data.loggedIn) {
  //         clearInterval(pollStatus);
  //         onLoginSuccess(res.data.token);
  //       }
  //     } catch (err) {
  //       setScanStatus('error');
  //     }
  //   }, 2000);
  //   return () => clearInterval(pollStatus);
  // }, [state, onLoginSuccess]);

  // useEffect(() => {
  //   const pollStatus = setInterval(async () => {
  //     try {
  //       const res = await axios.get('/api/auth/wechat/status', {
  //         params: { state }
  //       });
  //       if (res.data.loggedIn) {
  //         clearInterval(pollStatus);
  //         onLoginSuccess(res.data.token);
  //       }
  //     } catch (err) {
  //       setScanStatus('error');
  //     }
  //   }, 2000);
  //   return () => clearInterval(pollStatus);
  // }, [state, onLoginSuccess]);

  return (
    <div className="wechat-login">
      {scanStatus === 'waiting' && (
        <div className="qrcode-wrapper">
          <QRCodeSVG value={qrcodeUrl} size={200} />
          <p>微信扫码登录</p>
        </div>
      )}
    </div>
  );
}

WechatLogin.propTypes = {
  onLoginSuccess: PropTypes.func.isRequired
};

// Note: onLoginSuccess function is not defined in the original code, you may need to add it
function onLoginSuccess(token) {
  // Handle login success logic here
}
